/**
 * 封装请求方法
 * */
import axios from 'axios'
import qs from 'querystring'
// import router from '@/router'
// import Vue from 'vue'
import {
  Message,
  Loading
} from 'element-ui'

/**
 * 节流 -- 防止页面多个请求同时返回错误提示
 * @param {*} f 方法
 * @param {*} wait 等待时间
 */
function throttle(fn, wait = 1000) {
  let timer = null
  // 开始时间
  let startTime = Date.now()
  return (...args) => {
    // 触发时间
    let currentTime = Date.now()
    let context = this
    let remaining = wait - (currentTime - startTime)
    clearTimeout(timer)
    // 如果到了时间间隔点，就执行一次回调
    if (remaining <= 0) {
      fn.call(context, ...args)
      // 更新开始时间
      startTime = currentTime
    } else {
      // 保证方法在脱离事件后还会触发一次
      timer = setTimeout(fn, remaining)
    }
  }
}

/**
 * 错误提示
 * */
const errorLog = throttle(function(err) {
  // 显示提示
  Message({
    message: err.message,
    type: 'error',
    duration: 3 * 1000
  })
}, 1000)

/**
 * 成功提示
 * */
const successLog = throttle(function(msg) {
  // 显示提示
  Message({
    message: msg.message,
    type: 'success',
    duration: 3 * 1000
  })
}, 1000)

// 创建一个axios实例
const service = axios.create({
  // api的base_url
  // baseURL: 'http://192.168.36.14:8080',
  baseURL: 'http://192.168.36.7:8081',
  // 请求时间
  timeout: 30000,
  headers: { 'Content-Type': 'application/json; charset=utf-8' }
})
service.withCredentials = true

// 请求拦截器
let loading
service.interceptors.request.use(config => {
  let showLoading = true
  // 控制页面请求出现loading 效果
  if (showLoading) {
    loading = Loading.service({
      text: '加载中......',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
service.interceptors.response.use((response) => {
  // 关闭loading
  loading.close(response)
  if (response && response.data.code === 200) {
    if (response.config.method === 'post' || response.config.method === 'delete' || response.config.method === 'put') {
      successLog(response.data)
    }
    return response.data
  } else {
    errorLog(response.data)
  }
  return response.data
}, () => {
  const err = {
    message: '网络异常'
  }
  loading.close()
  errorLog(err)
})

/**
 * method  方法
 * url     请求地址
 * data    数据
 * show    控制如何传参数 true在url后面
 * */
export default function(method, url, data = null, show = false) {
  method = method.toLocaleLowerCase()
  if (method === 'get') {
    if (show) {
      return service.get(`${url}/${data.id}`)
    } else {
      return service.get(url, { params: data })
    }
  } else if (method === 'post') {
    return service.post(url, data)
  } else if (method === 'put') {
    if (show) {
      return service.put(`${url}?${qs.stringify(data)}`)
    } else {
      return service.put(url, data)
    }
  } else if (method === 'delete') {
    if (show) {
      return service.delete(`${url}/${data.id}`)
    } else {
      return service.delete(`${url}`, { params: data })
    }
  } else {
    console.log('......测测试')
  }
}
